<?php	ob_start();


    include_once 'includes/session.php';
    include_once 'includes/constants.php';
    include_once 'includes/functions.php';
    include_once 'testmail.php';

    $partners=new partners;
    $partners->connection($host,$user,$pass,$db);

#------------------------------------------------------------------------------
# getting variables
#------------------------------------------------------------------------------

# url to where cntrols should go after executing this page
   // $url 			= $_GET['url'];

# getting ip address
    $ipaddress		= $HTTP_SERVER_VARS['REMOTE_ADDR'];
	if(empty($ipaddress)) $ipaddress = $_SERVER['REMOTE_ADDR'];

# Merchantid
	$mid					=    trim($_GET['mid']);

# random no
   $leadRand				= trim($_GET['sec_id']);

# tranactionid
   $orderId				    = $_GET['orderId'];

	$referer 				= 	getenv(HTTP_REFERER);

# sub id
	$subid					= $_GET['subid'];

#------------------------------------------------------------------------------
# checking whether its a geniune lead request
#------------------------------------------------------------------------------

 # chacking whether the sale request is the outcome of a rececnt click
 # withing 60sec
 # from the same ip as click

 $unSql = "SELECT transaction_orderid FROM  partners_transaction WHERE transaction_orderid = '$orderId' AND transaction_referer='$referer' AND transaction_type='lead'" ;
 $unRet = @mysql_query($unSql);

 if(@mysql_num_rows($unRet)>0){
  # lead is by refresh
 }
 else{
   $sql = " SELECT * ,date_format(DATE_ADD( ipblocking_time, INTERVAL 60 MINUTE ),'%H/%i/%s/%d/%m/%y') as d ";
  $sql.= " FROM partners_ipblocking ";
  $sql.= " WHERE ipblocking_ipaddress = '$ipaddress'";
  $sql.= " And ipblocking_randNo = '$leadRand'  ";
  $sql.= " And ipblocking_merchantid= '$mid'  ";
  $ret = @mysql_query($sql);


  //if there is entry in ip block table
  if(mysql_num_rows($ret)>0){
     $row        = mysql_fetch_object($ret);
     $ipblock    = $row->d;
     $ipid       = $row->ipblocking_id;

	$mid         = $row->ipblocking_merchantid;
	$aid         = $row->ipblocking_affiliateid;
	$pgmid       = $row->ipblocking_programid;
	$joinid      = $row->ipblocking_joinpgmid;
	$linkid      = $row->ipblocking_linkid;
	$leadrate    = $row->ipblocking_lead;
	$statusid    = $row->ipblocking_statusid;

 # comparing last click and current click time
     if(!CompareTime($ipblock)) {
		//if not within ip block period

 		# updating lead
        GetTransaction($mid,$pgmid,$joinid,$aid,$linkid,$leadrate,$statusid,$minimum_amount,$admin_leadrate,$orderId,$subid) ;

		//update ip block table entry
        # updating last click time
        $sql  ="update partners_ipblocking set ipblocking_time=now(),ipblocking_randNo='$leadRand'  where ipblocking_id=$ipid";
        @mysql_query($sql);
     }
	 else
	 	# Added By DPT on 01/July/05
		# If within Ip block period then also mark the lead but merchant doesn't have to pay for this
	 	AddLeadTransaction($mid,$pgmid,$joinid,$aid,$linkid,$leadrate,$statusid,$minimum_amount,$admin_leadrate,$orderId,$subid);

  }
 }
#-------------------------------------------------------------------------------
# After recording the transaction the control is redirecting
# to the specified url
# with all post valus
#------------------------------------------------------------------------------
	/* $ch  = curl_init($url);
	 curl_setopt($ch, CURLOPT_SSLVERSION, 3);
	 curl_setopt($ch, CURLOPT_POST, 1);
	 curl_setopt($ch, CURLOPT_POSTFIELDS,$_POST);
	 $result=curl_exec ($ch);
	 curl_errno($ch);
	 curl_close ($ch);*/


# ------------------------------------------------------------------------------
# Function records the transctions
# And updates all required tables
#-------------------------------------------------------------------------------

function GetTransaction($mid,$pgmid,$joinid,$aid,$linkid,$leadrate,$statusid,$minimum_amount,$admin_leadrate,$orderId,$subid)
  {

# gets the http referer
   $referer				= getenv(HTTP_REFERER);

 // if admin has set up the lead rate in %, then calculate the same here
 if($GLOBALS['admin_leadrate_type']=="percentage") $admin_leadrate = ($leadrate*$admin_leadrate)/100;

# getting lead approval type
# ie whether it should be automatic approval or manual

  $sql1		=	"select * from partners_pgmstatus where pgmstatus_programid=$pgmid";
  $result	=	mysql_query($sql1)or die($sql1."<br/>".mysql_error());
  $row		=	mysql_fetch_object($result);

# getting approval type

  $approval			=	$row->pgmstatus_leadapproval;
  $mailmerchant 	=	$row->pgmstatus_mailmerchant;
  $mailaffiliate 	=	$row->pgmstatus_mailaffiliate;


  #  automatic approval
  if($approval=="automatic") {

  # set status to approved
     $approvalstatus = "approved";

  # get merchant account

  $sql        =	"SELECT *  FROM `merchant_pay`  WHERE pay_merchantid='$mid' ";
  $res        =	mysql_query($sql);
  $num		  =	mysql_num_rows($res);
  $cut_off    = $minimum_amount;
  if($num>0) {
      $row1               =   mysql_fetch_object($res);
      $merchant_balance   = $row1->pay_amount;
      if(($merchant_balance-($leadrate+$admin_leadrate) )<=$cut_off){
      }else
      {

	#---------------------------------------------------------------------------
    # Update Account info of admin,affil,merchant
    #---------------------------------------------------------------------------

	# Adding money to affiliate account
        $merchant_balance = $merchant_balance-($leadrate+$admin_leadrate);
        $sql1       ="SELECT *  FROM `affiliate_pay` where pay_affiliateid=$aid ";
        $res1       =mysql_query($sql1);
        echo @mysql_error();

        $num = mysql_num_rows($res1);
        if($num>0)
        {
           $row1       =  mysql_fetch_object($res1);
           $curamount  = $row1->pay_amount;
           $curamount  = $curamount+$leadrate;

           $sql2 ="update affiliate_pay set pay_amount='$curamount' where pay_affiliateid=$aid";
           $ret2 =mysql_query($sql2);
        }
        else
        {
           $sql2 ="INSERT INTO  affiliate_pay set pay_affiliateid=$aid , pay_amount='$leadrate'";
           $ret2 =mysql_query($sql2);
        }

    # affiliate account editing Ends here-

    # Subtract Money From Merchant Account
       $sql        = "UPDATE  `merchant_pay` SET  pay_amount=$merchant_balance  WHERE pay_merchantid='$mid' ";
       $res        = mysql_query($sql);
    # END OF  Subtract Money From Merchant Account

    # Adding To Admins Account

       $sql1      ="SELECT *  FROM `admin_pay`  ";
       $res1      =mysql_query($sql1);
       echo mysql_error();
       $num=mysql_num_rows($res1);
       if($num>0)
       {
          $row1   =   mysql_fetch_object($res1);
          $admin_curamount    = $row1->pay_amount;
          $admin_curamount    = $admin_curamount+$admin_leadrate;
       }

      $sql        ="UPDATE `admin_pay` SET `pay_amount` = '$admin_curamount'";
      $res        =mysql_query($sql);

	# END OF Adding to admin's account
   }
 }

    # END OF CODE  Added BY PRAMOD FOR UPDATE CURENT AMOUNT IN AFFIL,MERCHANT,ADMIN ACCOUNT


  $today         = date("Y-m-d");
  $admin_amount  = $admin_leadrate;
  $ip 			= $GLOBALS['REMOTE_ADDR'];

  //checking ip of user against offer available countries  jin on 6th Jul
  $user_ip = (ip2long($ip) < 0 ? -1 * ip2long($ip) : ip2long($ip));
  $temp_con = "OUT";

  $selq = "SELECT `program_countries`,`program_geotargeting_lead` FROM `partners_program` WHERE `program_id` = $pgmid";
  $row  = mysql_fetch_object(mysql_query($selq));
  $offer_in = explode(",",$row->program_countries);

  //if geo-targeting feature is enabled for click, then check whether the click is from allowed list of countries
  if($row->program_geotargeting_lead)
  {
	  for($cind=0;$cind<count($offer_in);$cind++){
	  $selq = "SELECT `ip_from`,`ip_to` FROM `partners_countryFlag` WHERE `country_name` = '".$offer_in[$cind]."'"
			  ." AND ip_from <=".$user_ip." AND `ip_to` >=".$user_ip."";
			if(mysql_num_rows(mysql_query($selq))) $temp_con = "IN";
	  }
   }
   else $temp_con = "IN";

  // add transaction
  if($temp_con == "OUT")
    $sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_ip,transaction_orderid,transaction_subid) values ($joinid,'lead','$approvalstatus','$today',0,'$linkid',0,'$referer','$ip','$orderId','$subid') ";
  else
  	$sql="INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_dateofpayment ,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_orderid,transaction_ip,transaction_subid) values ($joinid,'lead','$approvalstatus','$today',$leadrate,'$today','$linkid','$admin_amount','$referer','$orderId','$ip','$subid') ";
  mysql_query($sql);

 }
 else{
  $approvalstatus = "pending";          //manuall approval
  $today          = date("Y-m-d");
  $admin_amount   = $admin_leadrate;
  $ip 			= $GLOBALS['REMOTE_ADDR'];

  //checking ip of user against offer available countries  jin on 6th Jul
  $user_ip = (ip2long($ip) < 0 ? -1 * ip2long($ip) : ip2long($ip));
  $temp_con = "OUT";

  $selq = "SELECT `program_countries`,`program_geotargeting_lead` FROM `partners_program` WHERE `program_id` = $pgmid";
  $row  = mysql_fetch_object(mysql_query($selq));
  $offer_in = explode(",",$row->program_countries);

  //if geo-targeting feature is enabled for click, then check whether the click is from allowed list of countries
  if($row->program_geotargeting_lead)
  {
	  for($cind=0;$cind<count($offer_in);$cind++){
	  $selq = "SELECT `ip_from`,`ip_to` FROM `partners_countryFlag` WHERE `country_name` = '".$offer_in[$cind]."'"
			  ." AND ip_from <=".$user_ip." AND `ip_to` >=".$user_ip."";
			if(mysql_num_rows(mysql_query($selq))) $temp_con = "IN";
	  }
   }
   else $temp_con = "IN";

  // add transaction
  if($temp_con == "OUT")
    $sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_ip,transaction_orderid,transaction_subid) values ($joinid,'lead','$approvalstatus','$today',0,'$linkid',0,'$referer','$ip','$orderId','$subid') ";
  else
    $sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_orderid,transaction_ip,transaction_subid) values ($joinid,'lead','$approvalstatus','$today',$leadrate,'$linkid','$admin_amount','$referer','$orderId','$ip','$subid') ";
  mysql_query($sql);

 }
  # maling
 if ($mailmerchant =="yes") {
        MailMerchant($aid,$mid,$pgmid,$leadrate,$admin_leadrate,"lead");
 }
 if($mailaffiliate =="yes"){
        MailAffilaite($aid,$mid,$pgmid,$leadrate,"lead");
 }

}

 #---------------------------------------------------------------------------
 # Added By DPT on 01/July/05
 # if click is within IP block period mark the lead as transaction
 #---------------------------------------------------------------------------
function AddLeadTransaction($mid,$pgmid,$joinid,$aid,$linkid,$leadrate,$statusid,$minimum_amount,$admin_leadrate,$orderId,$subid)
  {

	# gets the http referer
	   $referer				= getenv(HTTP_REFERER);

	# getting lead approval type
	# ie whether it should be automatic approval or manual

	  $sql1		=	"select * from partners_pgmstatus where pgmstatus_programid=$pgmid";
	  $result	=	mysql_query($sql1)or die($sql1."<br/>".mysql_error());
	  $row		=	mysql_fetch_object($result);

	# getting approval type

	  $approval			=	$row->pgmstatus_leadapproval;
	  $mailmerchant 	=	$row->pgmstatus_mailmerchant;
	  $mailaffiliate 	=	$row->pgmstatus_mailaffiliate;

	  # amount will be 0 in this case
	  $admin_amount = 0;

		$today          = date("Y-m-d");
		$ip 			= $GLOBALS['REMOTE_ADDR'];

	  #  automatic approval
	  if($approval=="automatic")
	  {
           # set status to approved
           $approvalstatus = "approved";

          //checking ip of user against offer available countries  jin on 6th Jul
          $user_ip = (ip2long($ip) < 0 ? -1 * ip2long($ip) : ip2long($ip));
          $temp_con = "OUT";

	      $selq = "SELECT `program_countries`,`program_geotargeting_lead` FROM `partners_program` WHERE `program_id` = $pgmid";
	      $row  = mysql_fetch_object(mysql_query($selq));
	      $offer_in = explode(",",$row->program_countries);

		  //if geo-targeting feature is enabled for click, then check whether the click is from allowed list of countries
		  if($row->program_geotargeting_lead)
		  {
			  for($cind=0;$cind<count($offer_in);$cind++){
			  $selq = "SELECT `ip_from`,`ip_to` FROM `partners_countryFlag` WHERE `country_name` = '".$offer_in[$cind]."'"
					  ." AND ip_from <=".$user_ip." AND `ip_to` >=".$user_ip."";
					if(mysql_num_rows(mysql_query($selq))) $temp_con = "IN";
			  }
		   }
		   else $temp_con = "IN";

          // add transaction   jin on jul 06th
          if($temp_con == "OUT")
            $sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_ip,transaction_orderid,transaction_subid) values ($joinid,'lead','$approvalstatus','$today',0,'$linkid',0,'$referer','$ip','$orderId','$subid') ";
          else
			$sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_dateofpayment ,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_orderid,transaction_ip,transaction_subid) values ($joinid,'lead','$approvalstatus','$today',0,'$today','$linkid','$admin_amount','$referer','$orderId','$ip','$subid') ";
			mysql_query($sql);
	  }
	 else
	 {
          $approvalstatus = "pending";          //manuall approval

	      //checking ip of user against offer available countries  jin on 6th Jul
	      $user_ip = (ip2long($ip) < 0 ? -1 * ip2long($ip) : ip2long($ip));
	      $temp_con = "OUT";

	      $selq = "SELECT `program_countries`,`program_geotargeting_lead` FROM `partners_program` WHERE `program_id` = $pgmid";
	      $row  = mysql_fetch_object(mysql_query($selq));
	      $offer_in = explode(",",$row->program_countries);

		  //if geo-targeting feature is enabled for click, then check whether the click is from allowed list of countries
		  if($row->program_geotargeting_lead)
		  {
			  for($cind=0;$cind<count($offer_in);$cind++){
			  $selq = "SELECT `ip_from`,`ip_to` FROM `partners_countryFlag` WHERE `country_name` = '".$offer_in[$cind]."'"
					  ." AND ip_from <=".$user_ip." AND `ip_to` >=".$user_ip."";
					if(mysql_num_rows(mysql_query($selq))) $temp_con = "IN";
			  }
		   }
		   else $temp_con = "IN";

	      // add transaction
	      if($temp_con == "OUT")
	        $sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_ip,transaction_orderid,transaction_subid) values ($joinid,'lead','$approvalstatus','$today',0,'$linkid',0,'$referer','$ip','$orderId','$subid') ";
	      else
          	$sql = "INSERT into partners_transaction(transaction_joinpgmid,transaction_type,transaction_status,transaction_dateoftransaction,transaction_amttobepaid,transaction_linkid,transaction_admin_amount,transaction_referer,transaction_orderid,transaction_ip,transaction_subid) values ($joinid,'lead','$approvalstatus','$today',0,'$linkid','$admin_amount','$referer','$orderId','$ip','$subid') ";
     	  mysql_query($sql);
	 }

	 # maling
	 if ($mailmerchant =="yes") {
			MailMerchant($aid,$mid,$pgmid,0,0,"lead");
	 }
	 if($mailaffiliate =="yes"){
			MailAffilaite($aid,$mid,$pgmid,0,"lead");
	 }
}


 #-----------------------------------------------------------------------------
 # comparing date
 #----------------------------------------------------------------------------
function CompareTime($ipblock) {

	# making ot mktime foamt
             $dtarray       =explode("/",$ipblock);
             $iphour        =$dtarray[0];
             $ipminute      =$dtarray[1];
             $ipsecond      =$dtarray[2];
             $ipdate        =$dtarray[3];
             $ipmonth       =$dtarray[4];
             $ipyear        =$dtarray[5];

    # current
             $d=date("d");
             $m=date("m");
             $y=date("Y");
             $h=date("H");
             $i=date("i");
             $s=date("s");
             $today=mktime($h,$i,$s,$m,$d,$y)."<br/>";
             $ipblock= mktime($iphour,$ipminute,$ipsecond,$ipmonth,$ipdate,$ipyear);

    #compare time
             if($ipblock<$today)
                return true;
             else
                return false;

      }



?>